<template>

  <div>
    <el-form ref="form" :model="form" label-width="80px">
      <el-form-item v-if="chapterList!==null && chapterList.length!==0" label="章节" prop="classify">
        <el-select v-model="note.chapterId" placeholder="请选择" @change="changeChapter" :clearable="true">
          <el-option
            v-for="item in chapterList"
            :key="item.id"
            :label="item.chapterName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="分类" prop="classify">
        <el-select v-model="form.classify" placeholder="请选择" >
          <el-option
            v-for="item in classifyOption"
            :key="item.dictCode"
            :label="item.dictLabel"
            :value="item.dictCode"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input  v-model="form.title" placeholder="请输入标题" type="textarea" autosize/>
        <!--          <editor v-model="form.title" :min-height="192"/>-->
      </el-form-item>

      <el-form-item label="是否公开" prop="externalDisplay">
        <el-switch
          v-model="form.externalDisplay"
          :active-value="1"
          :inactive-value="0"
          active-color="#13ce66"
          inactive-color="#ff4949"
        >
        </el-switch>
      </el-form-item>
      <el-form-item label="内容" v-if=" find(contentItemIdArr,form.classify)">
        <editor v-model="form.content" :min-height="192"/>
      </el-form-item>
      <el-form-item label="网址" v-if=" find(arr4,form.classify)">
        <el-input v-model="form.content" placeholder="请输入网址"/>
      </el-form-item>
      <el-form-item label="音乐" v-if=" find(musicBtnIdArr,form.classify) ">
        <el-upload v-if="fileList.length===0"
                   :headers="authorization"
                   class="upload-demo"
                   :limit="1"
                   ref="upload"
                   name="file"
                   :action="uploadUrl"
                   :on-exceed="onExceed"
                   multiple
                   :accept="musicAccept"
                   :on-success="onSuccess"
        >
          <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
          <div slot="tip" class="el-upload__tip">只能上传mp3文件</div>
        </el-upload>
        <music v-if="fileList.length===1" :audioSrcs="fileList[0].url" :changeMusic="changeMusic"></music>
      </el-form-item>
      <el-form-item label="文件" v-if="find(downloadBtn,form.classify)">
        <el-upload v-if="fileList.length===0"
                   :headers="authorization"
                   class="upload-demo"
                   :limit="1"
                   ref="upload"
                   name="file"
                   :action="uploadUrl"
                   :on-exceed="onExceed"
                   multiple
                   :on-success="onSuccess"
        >
          <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>
        <div v-if="fileList.length===1">
          <el-input style="width: 95%"
                    v-model="form.content"
                    :disabled="true"
          >
          </el-input>
          <el-button size="small" type="primary" style="width: 5%" @click="deleteFile">删除文件</el-button>
        </div>

      </el-form-item>
      <el-form-item label="标签" prop="tag">
        <!--          <el-input v-model="form.tag" placeholder="请输入标签"/>-->
        <el-tag
          :key="tag.name"
          ref="upload"
          v-for="tag in  this.form.tag"
          closable
          :disable-transitions="false"
          :type="tag.type"
          :color="tag.color"
          :file-list="fileList"
          @close="handleClose(tag)"
        >
          {{ tag.name }}
        </el-tag>
        <el-input
          class="input-new-tag"
          v-if="inputVisible"
          v-model="inputValue"
          ref="saveTagInput"
          size="small"
          @keyup.enter.native="handleInputConfirm"
          @blur="handleInputConfirm"
        >
        </el-input>
        <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>

      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer" style="float: right">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </div>
</template>

<script>
import {listData} from '@/api/system/dict/data'
import {addNote, delNote, getNote, getTreeList, listNote, toChinesNum, updateNote} from '@/api/note/note'
import {Base64} from 'js-base64'
import {getToken} from '@/utils/auth'
import Music from '@/views/note/note/music'

export default {
  name: 'addNote',
  components: {Music},
  props: ['title', 'open', '_note', 'defaultClassify', '_chapterList'],
  data() {
    return {
      note: null,
      chapterList: [],
      musicAccept: '.mp3',
      //是否禁用title的修改
      disabledTitle: false,
      videoAccept: '.mp4',
      musicBtnIdArr: [105,124],
      contentItemIdArr: [101, 106, 109,125],
      downloadBtn: [107, 110, 111],
      arr4: [108],
      fileList: [],
      authorization: {Authorization: 'Bearer ' + getToken()}, // 上传的图片服务器地址
      uploadUrl: process.env.VUE_APP_BASE_API + '/file/upload', // 上传的图片服务器地址
      //浮动组件的配置
      floatForm: {
        themeColor: {
          hsl: {h: 200, s: 0, l: 0, a: 1},
          hex: '#000000',
          hex8: '#000000FF',
          rgba: {r: 0, g: 0, b: 0, a: 1},
          hsv: {h: 200, s: 0, v: 0, a: 1},
          oldHue: 200,
          source: 'hex',
          a: 1
        },
        fontSize: 20
      },
      headerShow: true,
      typeList: [],
      classifyOption: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 笔记表格数据
      noteList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        content: null,
        tag: [],
        classify: null,
        tree: null,
        deleted: null,
        newLabel: null
      },
      // 表单参数
      form: {
        classify: 100,
        title: null,
        content: null,
        tag: [],
        tree: null,
        deleted: null,
        newLabel: null,
        externalDisplay: 0
      },
      // 表单校验
      rules: {},
      // 标签
      dynamicTags: [],
      inputVisible: false,
      inputValue: '',
      //标签的类型
      tagTypes: ['success', 'info', 'warning', 'danger']
    }
  },
  created() {

    if (this._note) {
      console.log(' this._note', this._note)
      this.note = this._note
    }
    if (this._chapterList) {
      if (this._chapterList.length !== 0) {
        this.chapterList =JSON.parse(JSON.stringify(this._chapterList))
        for (let i = 0; i < this.chapterList.length; i++) {
          this.chapterList[i].chapterName = "第" + toChinesNum(i + 1) + "章  " + this.chapterList[i].chapterName
        }
      }
    }
    //初始化类型
    this.form.classify = this.defaultClassify ? this.defaultClassify : 100
    this.getList()
    listData({'dictType': 'zone_note_classify', 'pageSize': 99999}).then(response => {
      this.classifyOption = response.rows
    })
    if (this.note) {
      this.disabledTitle = true
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      this.handleUpdate(this.note.note)
      loading.close()
    } else {
      this.note = {
        'id': null,
        'chapterId': null
      }
    }
    if (this.chapterList) {
      if (!this._note) {
        this.note.chapterId = this.chapterList[this.chapterList.length - 1].id
        this.form.chapterId = this.chapterList[this.chapterList.length - 1].id
      }
    }
  },
  methods: {
    changeChapter(id) {
      this.$forceUpdate() //在下拉框上绑定change事件 更新视图 这样就不会有视图更新的问题
    },
    changeMusic() {
      this.fileList = []
    },
    //查找某个元素是否存在
    find(arr, val) {
      let value = arr.indexOf(val)
      // console.log("find(arr,val){",value!==-1)
      return value !== -1
    },
    //查找某个元素是否不存在
    findNot(arr, val) {
      let value = arr.indexOf(val)
      // console.log("find(arr,val){",value!==-1)
      return value === -1
    },
    deleteFile() {
      this.fileList = []
      this.form.content = ''
    },
    submitUpload() {
      this.$refs.upload.submit()
    },
    onExceed(files, fileList) {
      this.$alert('已达到限制')
    },
    onSuccess(files, fileList) {
      let title = files.data.name.substring(files.data.name.indexOf('-') + 1) + ''
      this.form.title = title
      this.form.content = files.data.url
      this.fileList.push(files.data)
    },
    closeLogin() {
      console.log(22222222)
    },
    /** 查询笔记列表 */
    getList() {
      this.loading = true
      console.log('getList', this.queryParams)
      listNote(this.queryParams).then(response => {
        this.noteList = response.rows
        this.total = response.total
        this.loading = false

      })
    },
    // 取消按钮
    cancel() {
      this.$emit('getList')
      this.$emit('notOpen')
    },
    // 表单重置
    async reset() {
      this.fileList = []
      this.form = {
        id: null,
        title: null,
        content: null,
        tag: null,
        classify: null,
        treeId: null,
        deleted: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        newLabel: null,
        externalDisplay: 1,
        remark: null
      }
      this.resetForm('form')
      getTreeList().then(res => {
        this.typeList = res.data
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加笔记'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getNote(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改笔记'
        this.form.tag = this.form.tag ? JSON.parse(this.form.tag) : []
        this.form.content = this.form.content ? Base64.decode(this.form.content) : null
        //转换数列表进行回显
        let treeIdArr = this.form.treeId ? this.form.treeId.split(',') : []
        this.form.treeId = []
        treeIdArr.forEach(treeId => {
          this.form.treeId.push(Number.parseInt(treeId))
        })
        if (this.form.classify === 105 || this.form.classify === 107) {
          let data = {
            'name': this.form.title,
            'url': this.form.content
          }
          this.fileList.push(data)
        }
        if (this.note) {
          this.form.chapterId = this.note.chapterId
        }
      })
    },
    /** 提交按钮 */
    submitForm() {
      //注入字典值
      this.classifyOption.forEach(e => {
        if (e.dictCode === this.form.classify) {
          this.form.classifyStr = e.dictLabel
        }
      })
      //获取标签
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.classify === 107 || this.form.classify === 105) {
            if (this.fileList.length === 0) {
              this.$alert('请上传一个文件')
              return
            }
          }
          this.form.content = this.form.content ? Base64.encode(this.form.content) : null
          this.form.tag = JSON.stringify(this.form.tag)
          this.form.treeId = this.form.treeId === null ? '' : this.form.treeId + ''

          if (this.form.id != null) {
            updateNote(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.note.note = response.data
              this.$emit('updateNode', this.note)
              this.$emit('getList')
              this.$emit('notOpen')
            })
          } else {
            addNote(this.form).then(response => {
              response.data.chapterId = this.form.chapterId
              this.$modal.msgSuccess('新增成功')
              // this.getList()
              this.$emit('getList')
              this.$emit('notOpen')
              response.data.chapterId = this.note.chapterId
              this.$emit('addNote', response)
            })
          }
        }
      })

    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除笔记编号为"' + ids + '"的数据项？').then(function () {
        return delNote(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('note/note/export', {
        ...this.queryParams
      }, `note_${new Date().getTime()}.xlsx`)
    },
    //关闭标签
    handleClose(tag) {
      console.log('this.form.tag', this.form.tag)
      // let parse = JSON.parse(this.form.tag);
      this.form.tag.splice(this.form.tag.indexOf(tag), 1)
    },
    //提交输入的标签
    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    /**
     * 添加到页面
     */
    handleInputConfirm() {
      let inputValue = this.inputValue
      console.log(this.form.tag)
      if (inputValue) {
        const len = Math.floor(Math.random() * this.tagTypes.length + 1) - 1
        // this.dynamicTags.push({"name": inputValue, "type": this.tagTypes[len], "color": "#BFEFFF"});
        console.log('this.form.tag', this.form.tag)
        this.form.tag = this.form.tag === null ? [] : this.form.tag
        this.form.tag.push({'name': inputValue, 'type': this.tagTypes[len], 'color': '#BFEFFF'})
      }
      // this.form.tag = JSON.stringify(this.dynamicTags)
      this.inputVisible = false
      this.inputValue = ''
    },
    closeMenuAndFloating() {
    }
  }
}

</script>

<style scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
